import { btoa } from 'buffer';
import process from 'process';
import path from 'path';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import autoprefixer from 'autoprefixer';
import postcssImport from 'postcss-import';
import { viteExternalsPlugin } from 'vite-plugin-externals';
import viteEjsPlugin from '@keenoho/vite-plugin-ejs';
import legacy from '@vitejs/plugin-legacy';
const rootPath = process.cwd();
const resolvePath = (filePath) => path.resolve(rootPath, filePath);

// ejs
function ejsRender(mode) {
  return viteEjsPlugin(function (config) {
    const appConf = config.env;
    return {
      ...config.env,
      appConf: btoa(encodeURIComponent(JSON.stringify(appConf))),
      mode,
      env: appConf.MODE,
    };
  });
}

// external
function externalsGenerator(mode) {
  let viteExternal, rollupExternal;
  if (mode === 'production') {
    viteExternal = {
      vue: 'Vue',
      vuex: 'Vuex',
      'vue-router': 'VueRouter',
      axios: 'axios',
    };
    rollupExternal = Object.keys(viteExternal);
  }
  return {
    viteExternal,
    rollupExternal,
  };
}

/**
 * 启动
 * command: serve, build, preview
 * mode: development production test
 * */
export default defineConfig(async ({ mode, command }) => {
  const { viteExternal, rollupExternal } = externalsGenerator(mode);
  return {
    root: rootPath,
    base: '/',
    mode,
    plugins: [
      ejsRender(mode), // ejs
      vue(), // vue
      viteExternalsPlugin(viteExternal), // extranal
      legacy(),
    ],
    publicDir: 'public',
    envDir: 'env',
    envPrefix: ['CONFIG'],
    css: {
      modules: {
        scopeBehaviour: 'global',
        generateScopedName: '[local]_[hash:base64:8]',
        localsConvention: 'camelCaseOnly',
      },
      postcss: {
        plugins: [autoprefixer(), postcssImport()],
      },
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
        },
      },
    },
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.css', '.less', '.vue'],
      alias: {
        '@': resolvePath('./src'),
      },
    },
    server: {
      cors: true,
      host: '0.0.0.0',
      port: 3000,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type,request-origin',
      },
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      assetsInlineLimit: 0,
      cssCodeSplit: true,
      emptyOutDir: true,
      sourcemap: false,
      modulePreload: true,
      manifest: true,
      copyPublicDir: true,
      rollupOptions: {
        input: {
          main: 'index.html',
        },
        external: rollupExternal,
      },
    },
    preview: {
      open: true,
      cors: true,
      host: '0.0.0.0',
      port: 3000,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type,request-origin',
      },
    },
  };
});
